/**
 * @file mhz.c
 * MHz source for TrayInfo.
 */

/* MHz support added by Laszlo Ashin <kodest@gmail.com> */

#include <stdio.h>
#include <stdlib.h>

#include "trayinfo.h"
#include "utils.h"

/** Source handle.*/
static source_handle_t *mhz_sh;

static int
mhz_write(double now, int fd)
{
	float mhz = 0;
	FILE *fp = fopen("/proc/cpuinfo", "rt");

	if (fp != NULL) {
		char buf[128];

		while (fgets(buf, sizeof(buf), fp) == buf) {
			char *s = buf;
			float core_mhz;

			if (!strstartswith(s, "cpu MHz")) {
				continue;
			}
			s = strchr(s, ':');
			if (s == NULL) {
				continue;
			}
			++s;
			if (sscanf(s, "%f", &core_mhz) != 1) {
				continue;
			}
			if (core_mhz > mhz) {
				mhz = core_mhz;
			}
		}
		fclose(fp);
	}

	if (mhz > 1.0f) {
		return show("%.0fMHz", mhz);
	}
	return 0;
}

int
init_module(module_phase_t phase)
{
	switch (phase) {
	case MODULE_PHASE_INIT: {
		source_t source = {
			.name = "mhz",
			.write = mhz_write,
		};
		mhz_sh = register_source(&source);
		return (mhz_sh == NULL);
	}
	case MODULE_PHASE_EXIT:
		return forget_source(mhz_sh);
	}

	return 0;
}
